<?php
require_once 'Interfaces/AIS_JsonPrcMethodParamsValidator.php';
require_once 'AIS_TypeValidationFunctionCreator.php';

/**
 * Thi Params validator uses the AIS_TypeValidationFunctionCreator to cache the validation
 * of a Json Object in a file so that it can execute it fastly.
 *
 */
class AIS_CachingObjectTypeCompatibiltyValidator implements AIS_JsonPrcMethodParamsValidator  {
	
	public function __construct()
	{
		$this->functionCreator = new AIS_TypeValidationFunctionCreator();
		$this->folder = dirname(__FILE__);
	}

	/**
	 * @see AIS_JsonPrcMethodParamsValidator::getErrorMessage()
	 * Returns always null
	 * @return AIS_ObjectTypeCompatibilityValidatorError
	 */
	public function getErrorMessage() {
		return null;
	}
	
	/**
	 * @see AIS_JsonPrcMethodParamsValidator::validate()
	 *
	 * @param ReflectionMethod $method
	 * @param array $params
	 * @return bool
	 */
	public function validate(ReflectionMethod $method, $params) {
		$functionName = $this->functionCreator->getValidationFunctionName($method);
		$file = $this->folder.'/'.$functionName.'.php';
		if (!file_exists($file))
		{
			$lockFile = $this->folder.'/'.'lock'.$functionName;
			$lh = fopen($lockFile,'a');
			if (flock($lh,LOCK_EX))
			{
				$this->functionCreator->addMethod($method);
				$this->functionCreator->generateValidationFunctions($file);
				flock($lh, LOCK_UN);
			}
			else 
			{
				while (!file_exists($file))
				{
					sleep(1);
				}
			}
			fclose($lh);
			
		}
		require_once $file;
		return $functionName($params);
	}
	/**
	 * Sets the folder where the files for caching are written.
	 *
	 * @param string $folder
	 */
	public function setFolder($folder)
	{
		$this->folder = $folder;
	}
	/**
	 * Enter description here...
	 *
	 * @var AIS_TypeValidationFunctionCreator
	 */
	private $functionCreator;
	/**
	 * 
	 *
	 * @var string
	 */
	private $folder = "";


}

?>